using System;
using System.Reflection;
using System.Threading;

using Iivil.Infrastructure;
using Iivil.Infrastructure.Logging;
using Iivil.Infrastructure.Logging.Providers;

namespace Iivil.Infrastructure.Logging {
	/// <summary>
	/// Summary description for ConfigurationProvider.
	/// </summary>
	public class LogProvider {
		private static ILogWriter _instance;
        private static Mutex _lock = new Mutex(false);

		public static ILogWriter Instance {
			get {
                lock (_lock) {
                    if (_instance == null) { 
                        _instance = new UserLogProvider();
                        AppDomain.CurrentDomain.DomainUnload += new EventHandler(DomainUnload);
                    }
                }
				return _instance;
			}
        }

        private static void DomainUnload(object sender, EventArgs e) {
            lock (_lock) {
                if (_instance == null)
                    return;
                _instance.Dispose();
                _instance = null;
            }
        }

        public static void SetInstance(ILogWriter instance)
        {
            lock (_lock)
            {
                if (_instance != null)
                    _instance.Dispose();
                _instance = instance;
            }
        }

        public static void WriteError(string category, string message)
        {
            Instance.WriteLogEntry(Severity.Error, category, message);
        }

        public static void WriteError(string category, string formatMessage, params object[] arg)
        {
            Instance.WriteLogEntry(Severity.Error, category, formatMessage, arg);
        }

        public static void WriteWarning(string category, string message)
        {
            Instance.WriteLogEntry(Severity.Warning, category, message);
        }

        public static void WriteWarning(string category, string formatMessage, params object[] arg)
        {
            Instance.WriteLogEntry(Severity.Warning, category, formatMessage, arg);
        }

        public static void WriteProgress(string category, string message)
        {
            Instance.WriteLogEntry(Severity.Progress, category, message);
        }

        public static void WriteProgress(string category, string formatMessage, params object[] arg)
        {
            Instance.WriteLogEntry(Severity.Progress, category, formatMessage, arg);
        }

        public static void WriteDebug(string category, string message)
        {
            Instance.WriteLogEntry(Severity.Debug, category, message);
        }

        public static void WriteDebug(string category, string formatMessage, params object[] arg)
        {
            Instance.WriteLogEntry(Severity.Debug, category, formatMessage, arg);
        }

    }
}
